<!-- ERC-备件管理-备件出库页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <TypeTree v-model:typeCode="typeCode" v-model:hasChildren="hasChildren" />
      <!-- 右侧整体功能 -->
      <div class="equip-table-wrap">
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="6">
              <px-form-item label="地块" prop="facCode">
                <px-select v-model="queryParams.facCode" placeholder="请选择地块" clearable filterable>
                  <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="保养计划编号">
                <px-input
                  v-model="queryParams.code"
                  clearable
                  placeholder="请输入保养计划编号"
                  autocomplete="off"
                  maxlength="50"
                  @blur="queryParams.code = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="保养名称">
                <px-input
                  v-model="queryParams.name"
                  clearable
                  placeholder="请输入保养名称"
                  autocomplete="off"
                  maxlength="50"
                  @blur="queryParams.name = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <div class="equip-table-btn">
          <px-button v-has="'ERC_EPM_PLAN_ADD'" :disabled="hasChildren" style="margin-right: 16px" type="primary" @click="handleAdd">
            新增保养计划
          </px-button>
          <px-button v-has="'ERC_EPM_PLAN_DELETE'" icon="Delete" plain type="danger" @click="handleBatchDel"> 批量删除 </px-button>
        </div>
        <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 304px)" border @selection-change="selectionChange">
          <px-table-column type="selection" min-width="40" align="center" />
          <px-table-column type="index" label="序号" min-width="60" align="center" fixed="left" />
          <px-table-column label="保养计划编号" minWidth="160" showOverflowTooltip fixed="left">
            <template #default="scope">
              <span v-if="isHasPermission('ERC_EPM_PLAN_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">
                {{ scope.row.code }}
              </span>
              <span v-else>{{ scope.row.code }}</span>
            </template>
          </px-table-column>
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template #default="scope">
              <span>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" min-width="180" align="center">
            <template #default="scope">
              <px-tooltip v-if="!scope.row.createTask" content="编辑" placement="top">
                <px-button v-has="'ERC_EPM_PLAN_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="详情" placement="top">
                <px-button v-has="'ERC_EPM_PLAN_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
              <px-tooltip v-if="!scope.row.createTask" content="删除" placement="top">
                <px-button v-has="'ERC_EPM_PLAN_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <AddPlan
      :isMain="isMain"
      :isView="isView"
      :typeCode="typeCode"
      :planData="planData"
      :drawerType="drawerType"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <PlanDetail :isView="isView" :typeCode="typeCode" :planData="planData" :drawerType="drawerType" @backMainPage="backMainPage" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_EPM_PLAN"
});
import { queryDictData } from "@/api/common";
import { delPlan, queryPlanList } from "@/api/erc/epm";
import { isHasPermission } from "@/utils/auth";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs, watch } from "vue";
import TypeTree from "../components/TypeTree.vue";
import AddPlan from "./components/AddPlan.vue";
import PlanDetail from "./components/PlanDetail.vue";

const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: false, // 查看true 新增/编辑false
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "name", label: "保养名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "facName", label: "所处地块", minWidth: "140", showOverflowTooltip: true },
    { prop: "startDate", label: "保养开始时间", minWidth: "140", showOverflowTooltip: true },
    { prop: "createTime", label: "计划创建时间", minWidth: "180", showOverflowTooltip: true },
    { prop: "userName", label: "保养负责人", minWidth: "140", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  typeCode: "",
  hasChildren: true,
  planData: "",
  drawerType: "",
  selectIds: [],
  facCodeList: []
});
const { isMain, isView, queryParams, tableColumns, tableData, total, typeCode, hasChildren, planData, drawerType, selectIds, facCodeList } =
  toRefs(state);

watch(
  () => typeCode.value,
  (newVal, oldVal) => {
    if (newVal) {
      queryTable();
    }
  }
);

// 表格多选框选中
function selectionChange(val: any) {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.code) {
      selectIds.value.push(item.code);
    }
  });
}

// 进入页面时触发
onMounted(async () => {
  queryTable();
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
});
// 查询备件列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await queryPlanList({ ...params, typeCode: typeCode.value });
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
const handleBatchDel = () => {
  PxMessageBox.confirm(`要删除所选中的保养计划吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delPlan({ codeList: selectIds.value });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

// 添加
const handleAdd = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};

// 编辑
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  planData.value = row;
  isMain.value = false;
  isView.value = false;
};

// 详情
const handleView = (row: any) => {
  drawerType.value = "view";
  planData.value = row;
  isMain.value = false;
  isView.value = true;
};

// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  planData.value = {};
  isMain.value = true;
  isView.value = false;
  drawerType.value = "";
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前保养计划吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delPlan({ codeList: [row.code] });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");
</style>
